package com.longma.server.exception;

import com.longma.server.constant.enums.ResponseCode;
import com.longma.server.pojo.UserResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理在用户认证出错时抛出的异常
 * @author HIBO
 *  AuthenticationEntryPoint 在用户认证出错时抛出的异常
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
            throws IOException {

        //没有凭证
        UserResponseEntity responseEntity = UserResponseEntity.fail(ResponseCode.AUTHENTICATION_FAIL);
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(responseEntity.toString());
    }
}
